<template>
  <div class="inventory-details">
    <c-table
      :data="tableData.pageData"
      :total="tableData.total"
      :columns="columns"
      size="small"
      :scroll="{ x: 1800 }"
      config
      :defaultConfig="defaultConfig"
      :derive="$btn('exportInventoryDetail')"
      @export="exportDetails"
      rowKey=" "
      :selection="isBatchDel"
      @onSelectChange="onSelectChange"
      :add="!isBuyer && $btn('inventoryAdd')"
      @onAdd="add"
      @onReload="reload"
      @pageChange="pageChange"
      :loading="loading"
    >
      <template v-slot:header-l>
        <template v-if="!isBuyer && $btn('inventoryBatchDel')">
          <template v-if="isBatchDel">
            <c-button type="danger" @click="cancelBatchDel">取消</c-button>
            <c-button
              type="success"
              @click="confirmBatchDel"
              :disabled="selectedKeys.length === 0"
              >确认</c-button
            >
            <span>已选择 {{ selectedKeys.length }} 个</span>
          </template>
          <c-button @click="batchDelHandle" v-else>批量删除</c-button>
        </template>
      </template>
      <template v-slot:category="{ row }">
        {{ row.categoryName }}
      </template>
      <template v-slot:warehouse="{ row }">
        {{ row.shortName }}
      </template>
      <template v-slot:createType="{ row }">
        {{ $getEnum(inventoryDict.createType, row) }}
      </template>
      <template v-slot:priceType="{ row }">
        <PriceType :flag="row" v-if="row.priceType" />
      </template>
      <template v-slot:saleDate="{ row }">
        {{ row ? $getTime(row) : undefined }}
      </template>
      <template v-slot:createDate="{ row }">
        {{ row ? $getTime(row) : undefined }}
      </template>
      <template v-slot:updateDate="{ row }">
        {{ row ? $getTime(row) : undefined }}
      </template>
      <template v-slot:customerCompany="{ row }">
        {{ row && row.companyNickname }}
      </template>
      <template v-slot:customerUser="{ row }">
        {{ row && row.realName }}
      </template>
      <template v-slot:customerPhone="{ row }">
        {{ row.customerUser && row.customerUser.phone }}
      </template>
      <template v-slot:handle="{ row }">
        <div class="handle" v-if="!isBuyer">
          <c-button
            type="link"
            @click="update(row)"
            v-if="$btn('inventoryUpdate') && !row.saleOrderCode"
            >编辑</c-button
          >
          <c-button type="link" @click="del(row)" v-if="$btn('inventoryDel')"
            >删除</c-button
          >
        </div>
      </template>
    </c-table>
    <ImportantHandle
      v-model="importantHandleVisible"
      :loading="importantHandleLoading"
      @submit="batchDel"
    />
  </div>
</template>

<script>
import {
  getInventoryDetails,
  deleteentityinventory,
  batchdeleteentityinventory,
  exportentityinventorydetail
} from "@/api/inventory";
import PriceType from "@/components-business/quotation/priceType";
import ImportantHandle from "@/components/important-handle";
import inventoryDict from "@/dict/inventory";
import companyDict from "@/dict/company";
import { mapState } from "vuex";
import { downloadFile } from "@/util/common";

const columns = [
  {
    title: "库存单号",
    dataIndex: "entityInventoryCode",
    width: 150,
    fixed: "left",
    hidden: false
  },
  {
    title: "品种",
    dataIndex: "category",
    scopedSlots: { customRender: "category" },
    hidden: false
  },
  {
    title: "品牌",
    dataIndex: "brand",
    hidden: false
  },
  {
    title: "规格",
    dataIndex: "spec",
    hidden: false
  },
  {
    title: "材质",
    dataIndex: "material",
    hidden: false
  },
  {
    title: "其他",
    dataIndex: "other",
    hidden: false
  },
  {
    title: "仓库",
    dataIndex: "warehouse",
    scopedSlots: { customRender: "warehouse" },
    hidden: false
  },
  {
    title: "库位号",
    dataIndex: "positionCode",
    hidden: false
  },
  {
    title: "材料号/捆包号",
    dataIndex: "materialCode",
    hidden: false
  },
  {
    title: "实重",
    dataIndex: "weight",
    hidden: false
  },
  {
    title: "入库单号",
    dataIndex: "entryOrderCode",
    hidden: false
  },
  {
    title: "备注",
    dataIndex: "remark",
    hidden: false
  },
  {
    title: "成本价（采购单价）",
    dataIndex: "purchasePrice",
    hidden: false
  },
  {
    title: "成本金额（采购总金额）",
    dataIndex: "totalPurchasePrice",
    hidden: false
  },
  {
    title: "入库提交人",
    dataIndex: "createUsername",
    hidden: false
  },
  {
    title: "入库时间",
    dataIndex: "createDate",
    scopedSlots: { customRender: "createDate" },
    hidden: false
  },
  {
    title: "最后更新时间",
    dataIndex: "updateDate",
    scopedSlots: { customRender: "updateDate" },
    hidden: false
  },
  {
    title: "入库方式", // 1、人工录入，2、商城采购
    dataIndex: "createType",
    scopedSlots: { customRender: "createType" },
    hidden: false
  },
  {
    title: "入库合同号",
    dataIndex: "entryContractCode",
    hidden: false
  },
  {
    title: "销售订单号",
    dataIndex: "saleOrderCode",
    hidden: false
  },
  {
    title: "客户公司",
    dataIndex: "customerCompany",
    scopedSlots: { customRender: "customerCompany" },
    hidden: false
  },
  {
    title: "下单人",
    dataIndex: "customerUser",
    scopedSlots: { customRender: "customerUser" },
    hidden: false
  },
  {
    title: "下单人手机",
    scopedSlots: { customRender: "customerPhone" },
    hidden: false
  },
  {
    title: "销售合同号",
    dataIndex: "saleContractCode",
    hidden: false
  },
  {
    title: "销售时间",
    dataIndex: "saleDate",
    scopedSlots: { customRender: "saleDate" },
    hidden: false
  },
  {
    title: "销售数量",
    dataIndex: "saleCount",
    hidden: false
  },
  {
    title: "提货方式",
    dataIndex: "deliveryType",
    hidden: false
  },
  {
    title: "作价方式",
    // dataIndex: "priceType",
    scopedSlots: { customRender: "priceType" },
    hidden: false
  },
  {
    title: "基价",
    dataIndex: "basePrice",
    hidden: false
  },
  {
    title: "升贴水",
    dataIndex: "premium",
    hidden: false
  },
  {
    title: "运杂费",
    dataIndex: "freight",
    hidden: false
  },
  {
    title: "销售单价（含税）",
    dataIndex: "taxPrice",
    hidden: false
  },
  {
    title: "销售金额",
    dataIndex: "saleAmount",
    hidden: false
  },
  {
    title: "操作",
    width: 50,
    fixed: "right",
    hidden: false,
    scopedSlots: { customRender: "handle" }
  }
];

export default {
  components: {
    PriceType,
    ImportantHandle
  },
  props: {
    searchKey: {
      type: String
    },
    categoryType: {
      type: Number
    }
  },
  data() {
    return {
      inventoryDict,
      loading: false,
      defaultConfig: [
        "entityInventoryCode",
        "category",
        "brand",
        "spec",
        "material",
        "other",
        "warehouse",
        "positionCode",
        "materialCode",
        "weight",
        "entryOrderCode",
        "saleOrderCode",
        "customerCompany",
        "customerUser",
        "customerPhone",
        "saleContractCode",
        "saleDate",
        "handle"
      ],
      tableData: {},
      columns,
      // tableColumns: [],
      pageNum: 1,
      isBatchDel: false, // 是否批量删除
      selectedKeys: [], // 选中的id
      importantHandleVisible: false, // 重大操作弹窗
      importantHandleLoading: false // 重大操作loading
    };
  },
  computed: {
    ...mapState(["user"]),
    // 是否买家，买家不能新增、删除
    isBuyer() {
      let companyDirection =
        this.user.company && this.user.company.companyDirection;
      let res = companyDirection === companyDict.companyDirection.buyer.value;
      return res;
    }
  },
  methods: {
    // 导出明细表
    exportDetails() {
      exportentityinventorydetail({
        categoryType: this.categoryType === 0 ? undefined : this.categoryType,
        searchKey: this.searchKey
      }).then(res => {
        downloadFile(res);
      });
    },
    // 前往编辑
    update(row) {
      this.$router.push({
        name: "inventoryUpdate",
        query: { id: row.id, version: row.version }
      });
    },
    // 删除
    del(row) {
      let _this = this;
      this.$confirm({
        title: "确认删除该实物库存吗？",
        onOk() {
          return new Promise((resolve, reject) => {
            deleteentityinventory({
              entityInventoryId: row.id,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.getDetails();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    batchDelHandle() {
      this.isBatchDel = true;
    },
    onSelectChange(keys) {
      this.selectedKeys = keys;
    },
    // 取消批量删除
    cancelBatchDel() {
      this.isBatchDel = false;
    },
    // 确认批量删除
    confirmBatchDel() {
      this.importantHandleVisible = true;
    },
    // 批量删除
    batchDel(data) {
      this.importantHandleLoading = true;
      batchdeleteentityinventory({
        entityInventoryIds: this.selectedKeys,
        password: data.password
      })
        .then(() => {
          this.$message.success("操作成功");
          this.importantHandleVisible = false;
          this.isBatchDel = false;
          this.reload();
        })
        .finally(() => {
          this.importantHandleLoading = false;
        });
    },
    search() {
      this.reload();
    },
    reload() {
      this.pageNum = 1;
      this.getDetails();
    },
    add() {
      this.$router.push({ name: "inventoryAdd" });
    },
    // 查询实物库存明细表
    getDetails() {
      this.loading = true;
      getInventoryDetails({
        categoryType: this.categoryType === 0 ? undefined : this.categoryType,
        searchKey: this.searchKey,
        pageData: {
          pageNum: this.pageNum,
          pageSize: 20
        }
      })
        .then(res => {
          this.tableData = res;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    pageChange(val) {
      this.pageNum = val;
      this.getDetails();
    }
  },
  created() {
    this.getDetails();
  }
};
</script>
